// utils/request.js
// 设置API的基础路径
import {
  baseUrl
} from "../config";
import login from '../model/login'

const request = (url, method, param, header = {}) => {
  return new Promise((resolve, reject) => {
    let token = wx.getStorageSync(login.TOKEN)
    wx.request({
      url: baseUrl + url, // 拼接完整的url
      method: method,
      data: param,
      header: {
        'App-Token': token,
        'Content-Type': 'application/json' // 设置请求的 header
      },
      async success(res) {
        const {
          statusCode,
          data
        } = res;
        console.log('http.request -------------------> http:   ' + url)
        if (statusCode >= 200 && statusCode < 300) {
          //未登录
          if (data.code == 401) {
            await login.login()
            const data = await request(url, method, param, header)
            resolve(data)
            return
          }
          if (data.code == 412) {
            wx.navigateTo({
              url: '/pages/auth/auth',
            })
            resolve('未授权手机号')
            return
          }

          // 请求成功的处理
          resolve(data);
        } else {
          // 可以根据项目需求处理HTTP错误
          reject(`网络请求错误，状态码${statusCode}`);
        }
      },
      fail(err) {
        // 请求失败的处理
        reject(err);
      }
    });
  });
};

// 导出封装的request方法
module.exports = {
  get: (url, data, header) => request(url, 'GET', data, header),
  post: (url, data, header) => request(url, 'POST', data, header),
  put: (url, data, header) => request(url, 'PUT', data, header),
  delete: (url, data, header) => request(url, 'DELETE', data, header),
  // ...可以根据需要封装更多的方法如patch等
};